package cn.zqy.demo3.day01.Jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * heima中account表 添加一条记录 insert 语句
 */
public class Demo02Insert {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        try {
            //1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取Connection对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/heima",
                    "root", "123456");
            //3.获取执行sql的对象 Statement
            statement = conn.createStatement();
            //4. 定义sql
            String sql = "insert into account values(null, '旺旺', 2000)";
            //5.执行sql   (sql执行影响的行数)
            int num = statement.executeUpdate(sql);

            //6.处理结果
            if (num > 0) {
                System.out.println("新增成功！！！");
            } else {
                System.out.println("添加失败！！");
            }



        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //7. 释放资源
            //避免空指针异常
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

